import React, { useEffect } from "react";
import { Space, Tag } from "antd";
import "./index.css";
import { useSelector, useDispatch } from "react-redux";
import { useNavigate, useLocation } from "react-router-dom";
import MenuConfig from "../../config";

const CommonTag = () => {
  const tabList = useSelector((state) => state.tab.tabList);
  const currentTab = useSelector((state) => state.tab.currentTab);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const handleClose = (tab, index) => {
    dispatch({ type: "tab/removeTab", payload: tab });
    if (tab.name !== currentTab.name) return;

    const lastIndex = tabList.length - 1;
    let nextTab;
    if (index === lastIndex) {
      nextTab = tabList[lastIndex - 1];
    } else {
      nextTab = tabList[index + 1];
    }
    dispatch({ type: "tab/setCurrentMenu", payload: nextTab });
    navigate(nextTab.path);
  };
  const handleChange = (tab) => {
    dispatch({ type: "tab/setCurrentMenu", payload: tab });
    navigate(tab.path);
  };
  const setTagList = (flag, item, index) => {
    return flag ? (
      <Tag
        key={item.path}
        closable={item.name !== "home"}
        color="#108ee9"
        onClose={() => handleClose(item, index)}
      >
        {item.label}
      </Tag>
    ) : (
      <Tag
        key={item.path}
        onClick={() => handleChange(item)}
        closable={item.name !== "home"}
        onClose={() => handleClose(item, index)}
      >
        {item.label}
      </Tag>
    );
  };
  return (
    <Space size={[0, 10]} className="common-tag" wrap>
      {tabList.map((item, index) =>
        setTagList(item.name === currentTab.name, item, index)
      )}
    </Space>
  );
};
export default CommonTag;
